﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using AutoMail.Data;
using AutoMail.Models;
using AutoMail.Service.Interface;
using AutoMail.QuartzJobs.Interfaces;

namespace AutoMail.Controllers
{
    public class EmailJobsController : Controller
    {
        private readonly AutoMailContext _context;
        private readonly IQuartzService _quartzService;
        private readonly IJobsManager _jobsManager;

        public EmailJobsController(AutoMailContext context, IQuartzService quartzService, IJobsManager jobsManager)
        {
            _context = context;
            _quartzService = quartzService;
            _jobsManager = jobsManager;
        }

        // GET: EmailJobs
        public async Task<IActionResult> Index()
        {
              return _context.EmailJob != null ? 
                          View(await _context.EmailJob.ToListAsync()) :
                          Problem("Entity set 'AutoMailContext.EmailJob'  is null.");
        }

        // GET: EmailJobs/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.EmailJob == null)
            {
                return NotFound();
            }

            var emailJob = await _context.EmailJob
                .FirstOrDefaultAsync(m => m.Id == id);
            if (emailJob == null)
            {
                return NotFound();
            }

            return View(emailJob);
        }

        // GET: EmailJobs/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: EmailJobs/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,StaffName,Sex,BirthDay,Email,EmailBody,ComeToCompanyDate")] EmailJob emailJob)
        {
            if (ModelState.IsValid)
            {
                _context.Add(emailJob);
                await _context.SaveChangesAsync();

                var emailJobN = _context.EmailJob.Single(t => 
                    t.StaffName == emailJob.StaffName 
                    && t.Sex == emailJob.Sex 
                    && t.Email == emailJob.Email);

                // Create related Quartz jobs
                await _jobsManager.ScheduleNewOrModifyJobs(_quartzService.GetCurrentScheduler(), new List<EmailJob>() { emailJobN });

                return RedirectToAction(nameof(Index));
            }

            return View(emailJob);
        }

        // GET: EmailJobs/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.EmailJob == null)
            {
                return NotFound();
            }

            var emailJob = await _context.EmailJob.FindAsync(id);
            if (emailJob == null)
            {
                return NotFound();
            }
            return View(emailJob);
        }

        // POST: EmailJobs/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int? id, [Bind("Id,StaffName,Sex,BirthDay,Email,EmailBody,ComeToCompanyDate")] EmailJob emailJob)
        {
            if (id != emailJob.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(emailJob);
                    await _context.SaveChangesAsync();

                    // Update related Quartz jobs
                    await _jobsManager.ScheduleNewOrModifyJobs(_quartzService.GetCurrentScheduler(), new List<EmailJob>() { emailJob });
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmailJobExists(emailJob.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }

            return View(emailJob);
        }

        // GET: EmailJobs/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.EmailJob == null)
            {
                return NotFound();
            }

            var emailJob = await _context.EmailJob
                .FirstOrDefaultAsync(m => m.Id == id);
            if (emailJob == null)
            {
                return NotFound();
            }

            return View(emailJob);
        }

        // POST: EmailJobs/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int? id)
        {
            if (_context.EmailJob == null)
            {
                return Problem("Entity set 'AutoMailContext.EmailJob'  is null.");
            }
            var emailJob = await _context.EmailJob.FindAsync(id);
            if (emailJob != null)
            {
                _context.EmailJob.Remove(emailJob);
            }
            
            await _context.SaveChangesAsync();

            // Delete related email sending schedule
            await _jobsManager.DeleteJobsOfOneStaff(_quartzService.GetCurrentScheduler(), emailJob);

            return RedirectToAction(nameof(Index));
        }

        private bool EmailJobExists(int? id)
        {
          return (_context.EmailJob?.Any(e => e.Id == id)).GetValueOrDefault();
        }

        public IActionResult Privacy()
        {
            return View();
        }
    }
}
